/**
 * 随机生成 指定层级/指定length 的树
 */
const fs = require('fs')

let id = 1
class Node {
  constructor() {
    this.id = id
    this.name = `name-${id}`
    this.children = []
    id++
  }
}

function random (min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

function generateRandomTree (options) {
  const { length, level, childrenLength } = options
  const res = []
  let maxDepth = 0
  let maxChildLength = 0
  function fn (totalLen, currentLevel = 1, currentChildren = res, depth = 1) {
    if (currentLevel > level) return
    for (let i = 0; i < totalLen; i++) {
      const node = new Node
      let _level = currentLevel
      if (currentLevel === 1) {
        const randomLevel = random(1, level)
        _level = randomLevel
      }
      maxDepth = Math.max(maxDepth, depth)
      fn2(node, _level, childrenLength, currentChildren, depth)
    }
  }

  function fn2 (node, randomLevel, length, currentChildren, depth) {
    const children = node.children
    const randomLen = random(0, length)
    currentChildren.push(node)
    maxChildLength = Math.max(maxChildLength, currentChildren.length)
    fn(randomLen, randomLevel + 1, children, depth + 1)
  }

  fn(length)

  // 保证 最大深度和最多孩子 的存在
  while (maxDepth < level || maxChildLength < childrenLength) {
    res.length = 0
    fn(length)
  }

  return res
}

const res = generateRandomTree({
  // 100项的数组长度
  length: 100,
  // 最大深度为3,每一项数据的深度不确定，但是至少有一项数据的深度为最大深度
  level: 3,
  // 最多孩子的数量为2,每一项孩子的数量不固定，但是至少有一项数据的孩子数量为2
  childrenLength: 2,
})


fs.writeFileSync('./test.json', JSON.stringify(res))
